/*
 *      Copyright 2012  Samsung Electronics Co., Ltd
 *
 *      Licensed under the Flora License, Version 1.0 (the "License");
 *      you may not use this file except in compliance with the License.
 *      You may obtain a copy of the License at
 *
 *              http://www.tizenopensource.org/license
 *
 *      Unless required by applicable law or agreed to in writing, software
 *      distributed under the License is distributed on an "AS IS" BASIS,
 *      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *      See the License for the specific language governing permissions and
 *      limitations under the License.
 */

var gListenerId;

$(document).delegate("#main", "pageinit", function() {
	$("#main .ui-btn-back").bind("vclick", function() {
		exitOrHide();
		return false;
	});
	$("#list-running").bind("vclick", function() {
		listRunningApps();
		return false;
	});
	$("#list-installed").bind("vclick", function() {
		listInstalledApps();
		return false;
	});
	$("#select-image").bind("vclick", function() {
		selectImage();
		return false;
	});
	$("#app-list").delegate("div", "vclick", function() {
		var id = $(this).parent().data("id");

		if ($(this).parent().data("app-list-type") == "installed") {
			launchApp(id);
		} else {
			killApp(id);
		}
		return false;
	});

	gListenerId = tizen.application.addAppInfoEventListener({
		oninstalled: function(app) {
			alert("Tracking message :<br/>" + app.name + " installed");
		},
		onupdated: function(app) {
			alert("Tracking message :<br/>" + app.name + " updated");
		},
		onuninstalled: function(appid) {
			alert("Tracking message :<br/>The app " + appid + " uninstalled");
		}
	});

	listInstalledApps();
});

function exitOrHide() {
	if (confirm("Exit or hide?<br/><br/>(OK:Exit  Cancel:Hide)") == true) {
		tizen.application.removeAppInfoEventListener(gListenerId);
		tizen.application.exit();
	} else {
		tizen.application.hide();
	}
}

function makeListItem(type, id, name, appId, icon) {
	return '<li class="ui-li-has-multiline" data-app-list-type="'
		+ type
		+'" data-id="'
		+ id
		+ '"><img src="'
		+ icon
		+ '" class="ui-li-bigicon">'
		+ name
		+ '<span class="ui-li-text-sub">'
		+ appId
		+ '</span><div data-role="button" data-inline="true">'
		+ (type == "installed" ? "Launch" : "Kill")
		+ '</div></li>';
}

function onGetAppsInfoSuccess(apps) {
	var app, str = '<li data-role="list-divider">Installed applications</li>';

	for (var i = 0; i < apps.length; i++) {
		app = apps[i];
		if(app.show == true) {
			str += makeListItem("installed", app.id, app.name, app.id, app.iconPath);
		}
	}

	$("#app-list").html(str).trigger("create").listview("refresh");
}

function onGetAppsInfoError(err) {
	alert("getAppsInfo failed : " + err.message);
}

function listInstalledApps() {
	try {
		/* get the list of installed applications */
		tizen.application.getAppsInfo(onGetAppsInfoSuccess, onGetAppsInfoError);
	} catch (exc) {
		alert("getAppsInfo exc:" + exc.message);
	}
}

function onGetAppsContextSuccess(contexts) {
	var app, str = '<li data-role="list-divider">Running applications</li>';

	for (var i = 0; i < contexts.length; i++) {
		app = tizen.application.getAppInfo(contexts[i].appId);
		if(app.show == true) {
			str += makeListItem("running", contexts[i].id, app.name, app.id, app.iconPath);
		}
	}

	$("#app-list").html(str).trigger("create").listview("refresh");
}

function onGetAppsContextError(err) {
	alert("getAppsContext exc:" + err.message);
}

function listRunningApps() {
	try {
		tizen.application.getAppsContext(onGetAppsContextSuccess, onGetAppsContextError);
	} catch (exc) {
		alert("getAppsContext exc: " + exc.message);
	}
}

function launchApp(id) {
	function onSuccess() {
		console.log(id + " launched successfully!");
	}

	function onError(err) {
		alert("launch failed : " + err.message);
	}

	try {
		tizen.application.launch(id, onSuccess, onError);
	} catch (exc) {
		alert("launch exc:" + exc.message);
	}
}

function killApp(id) {
	var appName = tizen.application.getAppInfo(tizen.application.getAppContext(id).appId).name;

	function onSuccess() {
		console.log(appName + " killed successfully!");
		listRunningApps();
	}

	function onError(err) {
		alert("kill failed : " + err.message);
	}

	if(confirm("Do you really want to kill " + appName +"?") == false) {
		return;
	}

	try {
		tizen.application.kill(id, onSuccess, onError);
	} catch (exc) {
		alert("kill exc:" + exc.messagesage);
	}
}

function selectImage() {
	var service = new tizen.ApplicationService(
			"http://tizen.org/appcontrol/operation/pick", null, "image/*");

	function onSuccess() {
		console.log("Appservice launched");
	}

	function onError() {
		alert("Appservice launch failed: " + err.message);
	}

	var serviceReply = {
		onsuccess : function(reply) {
			alert("Selected image path : <br/>" + reply[0].value[0]);
		},
		onfail : function() {
			alert("Appservice request failed");
		}
	};

	try {
		tizen.application.launchService(service, null, onSuccess, onError, serviceReply);
	} catch (exc) {
		alert("launchService exc: " + exc.message);
	}
}